<template>
  <page-container :title="route.meta.title">
    <SearchTable
      ref="tableRef"
      :table-list-api="tableListApi"
      :columns="columns"
      :show-selection="true"
      :convert-from-response="res => res.data"
    >
      <template #searchItems="{ colProps, formState }">
        <a-col v-bind="colProps">
          <a-form-item name="start_at|end_at" label="起止时间">
            <a-range-picker v-model:value="formState['start_at|end_at']" style="width: 100%" allow-clear />
          </a-form-item>
        </a-col>
      </template>

      <template #tableBtns="{ selectedRowsData }">
        <a-button
          type="primary"
          :disabled="!selectedRowsData.length"
          @click="handleBatchEnable(selectedRowsData, true)"
        >
          批量上线
        </a-button>
        <a-button
          type="primary"
          :disabled="!selectedRowsData.length"
          @click="handleBatchEnable(selectedRowsData, false)"
        >
          批量下线
        </a-button>
      </template>
    </SearchTable>
    <DialogViewer v-if="pageType === PAGE_TYPE.VIEW" :form-data="formData" :items="columns" @cancel="handleCancel" />

    <a-modal :open="auditVisible" :width="680" title="风控" @ok="handleOk" @cancel="handleCancel">
      <a-descriptions v-if="auditState.data" :column="2" :label-style="{ fontWeight: 600 }">
        <a-descriptions-item v-for="item of computedDisplayItems" :key="item.dataIndex" :label="item.title">
          {{ ((text = getItemText(item)), void 0) }}
          <div class="ellipsis" :title="text">{{ text }}</div>
        </a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-form ref="formRef" :model="auditState" :label-col="{ span: 4, offset: 0 }">
        <a-form-item v-if="auditState.data" required name="enabled" label="是否通过风控">
          <a-radio-group v-model:value="auditState.enabled">
            <a-radio :value="true">通过</a-radio>
            <a-radio :value="false">驳回</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="remark" label="备注" :rules="computedFormRules.remark">
          <a-textarea v-model:value="auditState.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </page-container>
</template>

<script setup lang="tsx">
import { useRoute } from 'vue-router';
import request from '@/utils/request';
import SearchTable from '@/components/SearchTable';
import useTablePage, { PAGE_TYPE } from '@/hooks/useTablePage';
import type { IAuditParams, IColumn, IOption, IRow } from '@/types';
import type { FormInstance } from 'ant-design-vue/es/form';
import { useUserStore } from '@/store';
import { enabledAd } from '@/api/adRisk';
import { getMedias } from '@/api/medium';

const route = useRoute();
const { pageType } = useTablePage();
const tableListApi = '/v1/adrisk/list';
const tableRef = ref();
const userStore = useUserStore();
const auditOptions = [
  { value: '0', label: '未风控' },
  { value: '1', label: '风控通过' },
  { value: '2', label: '风控拒绝' },
];

const isMediaRole = computed(() => userStore.role === 'media');

const columns = computed(() => {
  const cols: IColumn[] = [
    {
      title: '媒体方',
      width: 80,
      dataIndex: 'media_id',
      type: 'enum',
      required: true,
      searchable: true,
      options: mediaOptions.value,
      customRender: ({ record }) => {
        const found = mediaOptions.value.find(option => option.value === record.media_id);
        return found?.label || '';
      },
    },
    {
      title: '应用',
      width: 80,
      dataIndex: 'app_id',
      type: 'enum',
      required: true,
      searchable: true,
      options: appOptions.value,
      customRender: ({ record }) => {
        const found = appOptions.value.find(option => option.value === record.app_id);
        return found?.label || '';
      },
    },
    {
      title: '广告位',
      width: 80,
      dataIndex: 'ad_site_id',
      type: 'enum',
      required: true,
      searchable: true,
      options: adSiteOptions.value,
      customRender: ({ record }) => {
        const found = adSiteOptions.value.find(option => option.value === record.ad_site_id);
        return found?.label || '';
      },
    },
    {
      title: '广告id',
      width: 120,
      dataIndex: 'adid',
    },
    {
      title: '第三方平台',
      width: 100,
      dataIndex: 'third_ad_platform',
    },
    {
      title: '广告图片url',
      width: 120,
      dataIndex: 'ad_url',
      customRender: ({ record }) => {
        return (
          <div style={{ maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            <a href={record.ad_url} target="_blank" title={record.ad_url}>
              {record.ad_url}
            </a>
          </div>
        );
      },
    },
    {
      title: '广告跳转类型', //必填
      width: 120,
      dataIndex: 'ad_action',
    },
    {
      title: '广告有效期',
      width: 90,
      dataIndex: 'ad_time',
    },
    {
      title: '广告状态',
      width: 80,
      dataIndex: 'ad_status',
    },
    {
      title: '来源',
      width: 60,
      dataIndex: 'from',
    },
    {
      title: '平台审核状态',
      width: 110,
      type: 'enum',
      dataIndex: 'platform_risk',
      searchable: true,
      options: auditOptions,
    },
    {
      title: '平台审核备注',
      width: 110,
      dataIndex: 'platform_risk_remark',
    },
    {
      title: '媒体方审核状态',
      width: 120,
      type: 'enum',
      dataIndex: 'media_risk',
      searchable: true,
      options: auditOptions,
    },
    {
      title: '媒体方审核备注',
      width: 120,
      dataIndex: 'media_risk_remark',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      customRender: ({ record }) => {
        // 当平台方审核状态=1或者=0的时候 媒体方的审核按钮才能让点击
        const auditDisabled = isMediaRole.value ? record.platform_risk == '2' : false;

        const btns = [
          <a-button size="small" type="link" onClick={() => handleGeting(record)}>
            查看
          </a-button>,
          <a-button
            size="small"
            type="link"
            disabled={auditDisabled}
            onClick={() => handleAudit(record.id, true, record)}
          >
            审核
          </a-button>,
        ];

        return btns;
      },
    },
  ];

  // 媒体方角色不展示 平台审核状态、平台审核备注
  // if (userStore.role === 'media') {
  //   const index = cols.findIndex(c => c.dataIndex === 'platform_risk');
  //   cols.splice(index, 2);
  // }

  return cols;
});

const formData = ref<IRow>();
const handleGeting = (record: IRow) => {
  formData.value = record;
  pageType.value = PAGE_TYPE.VIEW;
};
const formRef = ref<FormInstance>();
const handleOk = async () => {
  await formRef.value?.validate();
  const { ids, enabled, remark } = auditState.value;
  enabledAd(ids, enabled, remark).then(() => {
    tableRef.value.refreshTable();
    handleCancel();
  });
};
const handleCancel = () => {
  formRef.value?.resetFields();
  auditVisible.value = false;
  pageType.value = null;
};

const computedDisplayItems = computed(() => {
  const cols = columns.value.filter(item => item.dataIndex !== 'action');
  return cols;
});

const getItemText = (item: IColumn) => {
  const text = auditState.value.data?.[item.dataIndex];
  if (item.customRender) {
    // @ts-ignore
    const result = item.customRender({ text, record: auditState.value.data });
    if (typeof result === 'string') {
      return result;
    }
  }
  if (item.type === 'boolean') {
    return text ? item.switchLabels?.[0] : item.switchLabels?.[1];
  }
  if (item.type === 'enum') {
    return item.options?.find(o => o.value === text)?.label;
  }
  return text;
};

const handleBatchEnable = (selectedRowsData: IRow[], enabled: boolean) => {
  const ids = selectedRowsData.map(({ id }) => id);
  handleAudit(ids, enabled);
};

const auditVisible = ref(false);
const auditState = ref<IAuditParams>({ ids: '', enabled: true, remark: '' });
const handleAudit = (ids: string | string[], enabled?: boolean, record?: IRow) => {
  auditState.value = {
    ids,
    enabled: enabled ?? true,
    remark: '',
    data: record,
  };
  auditVisible.value = true;
};
// 使用 computed 来动态生成备注的验证规则
const computedFormRules = computed(() => {
  return {
    remark: [
      // 当选中“驳回”（即 auditState.enabled 为 false）时，备注为必填
      { required: !auditState.value.enabled, message: '备注为必填项', trigger: 'blur' },
    ],
  };
});
const mediaOptions = ref<IOption[]>([]);
const appOptions = ref<IOption[]>([]);
const adSiteOptions = ref<IOption[]>([]);
const setMediaOptions = async () => {
  const data = await getMedias({ page: 1, page_size: 100 });
  mediaOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setMediaOptions();
const setAppOptions = async () => {
  const data = await request.get('/v1/app/list', { params: { page: 1, page_size: 100 } });
  // @ts-ignore
  appOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setAppOptions();

const setAdSiteOptions = async () => {
  const data = await request.get('/v1/adsite/list', { params: { page: 1, page_size: 100 } });
  adSiteOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setAdSiteOptions();
</script>

<style>
.ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 这将限制文本显示为3行 */
  -webkit-box-orient: vertical;
}
</style>
